Skip to content

Comments

feat: chain manager with longest-chain fork resolution and state replay#33

Closed
arunabha003 wants to merge 27 commits intoStabilityNexus:mainfrom
arunabha003:issue-8-chain-manager-fork-resolution
Closed

feat: chain manager with longest-chain fork resolution and state replay#33
arunabha003 wants to merge 27 commits intoStabilityNexus:mainfrom
arunabha003:issue-8-chain-manager-fork-resolution

Conversation

@arunabha003
Copy link

@arunabha003 arunabha003 commented Feb 23, 2026

Addressed Issues:

Part of #8
Depends on #31

Summary

  • Add ChainManager to track canonical chain, block index, and canonical state
  • Validate incoming blocks against parent linkage, merkle commitment, expected difficulty target, and PoW
  • Store valid side-fork blocks
  • Reorganize to longer forks using full state replay from genesis (safe revert + replay semantics)
  • Expose helpers for canonical lookup and expected next difficulty
  • Add tests for:
    • normal tip extension
    • longer-fork reorg and resulting state correctness
    • rejection of unknown-parent blocks
    • rejection of invalid coinbase/state transitions
    • rejection of wrong difficulty target

Validation

  • python -m ruff check src tests
  • python -m pytest

Checklist

  • [x ] My PR addresses a single issue, fixes a single bug or makes a single improvement.
  • [ x] My code follows the project's code style and conventions.
  • [ x] If applicable, I have made corresponding changes or additions to the documentation.
  • [ x] If applicable, I have made corresponding changes or additions to tests.
  • [ x] My changes generate no new warnings or errors.
  • [ x] I have joined the Stability Nexus's Discord server and I will share a link to this PR with the project maintainers there.
  • [ x] I have read the Contribution Guidelines.
  • [ x] Once I submit my PR, CodeRabbit AI will automatically review it and I will address CodeRabbit's comments.

AI Usage Disclosure

Check one of the checkboxes below:

  • This PR does not contain AI-generated code at all.
  • [ x] This PR contains AI-generated code. I have tested the code locally and I am responsible for it.

I have used the following AI models and tools: TODO

⚠️ AI Notice - Important!

We encourage contributors to use AI tools responsibly when creating Pull Requests. While AI can be a valuable aid, it is essential to ensure that your contributions meet the task requirements, build successfully, include relevant tests, and pass all linters. Submissions that do not meet these standards may be closed without warning to maintain the quality and integrity of the project. Please take the time to understand the changes you are proposing and their impact.

Summary by CodeRabbit

Release Notes

  • New Features

    • Implemented blockchain with block validation, transaction processing, and chain management
    • Added Proof-of-Work consensus with dynamic difficulty adjustment
    • Introduced cryptographic key generation, signing, and address derivation
    • Created transaction mempool with fee-based prioritization and eviction
    • Added account state management with atomic block application
    • Implemented genesis block initialization and configuration
    • Added CLI node entrypoint for running the network
  • Chores

    • Added CI/CD automation
    • Configured project tooling and dependencies
    • Updated documentation with setup instructions
  • Tests

    • Added comprehensive test coverage for all blockchain components

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 23, 2026

Caution

Review failed

Failed to post review comments

Walkthrough

Introduces a complete blockchain implementation scaffold with core primitives (blocks, transactions, state, consensus), a fee-based mempool with nonce ordering, dynamic difficulty adjustment, canonical serialization, and comprehensive test coverage alongside build tooling.

Changes

Cohort / File(s) Summary
Build & Configuration
.github/workflows/ci.yml, Makefile, pyproject.toml, .gitignore, README.md, src/minichain/__init__.py
Added CI workflow (checkout, Python 3.11, lint, test), Makefile with install/dev-install/test/lint/format targets, pyproject.toml with project metadata and console script entry point, .gitignore entries for cache/venv/docs, README refactored to focus on setup and repository layout, package initialization with version declaration.
Block & Consensus
src/minichain/block.py, src/minichain/consensus.py, src/minichain/merkle.py
BlockHeader and Block definitions with hash(), merkle root validation, and coinbase verification; PoW consensus via is_valid_pow, difficulty retargeting (compute_next_difficulty_target), and mine_block_header with nonce search and stop event support; Merkle tree construction with leaf duplication for odd counts.
Transactions & Signatures
src/minichain/transaction.py, src/minichain/crypto.py, src/minichain/serialization.py
Transaction dataclass with signing/verification and coinbase support; Ed25519 key pair generation, serialization, address derivation (Blake2b-based), and signature verification with PyNaCl runtime checks; deterministic canonical JSON serialization for transactions and block headers with strict field ordering.
State & Storage
src/minichain/state.py, src/minichain/genesis.py, src/minichain/storage.py
Account state with balance/nonce tracking, atomic block application with rollback on transaction failure, and StateTransitionError handling; genesis block/state initialization with validation of initial balances and difficulty; placeholder storage module.
Chain Management & Mempool
src/minichain/chain.py, src/minichain/mempool.py
ChainManager maintaining blocks, canonical chain path, and tip; block addition with duplicate detection, parent validation, state replay, and fork resolution via longest-chain rule; Mempool with transaction deduplication, per-sender nonce tracking, fee-based mining selection with ready/waiting pools, stale eviction, and revalidation after block confirmations.
Node & Network
src/minichain/node.py, src/minichain/network.py, src/minichain/__main__.py
Node orchestration scaffold with start_node(host, port) placeholder for Issue #20; CLI argument parser (build_parser) with default host and port; placeholder P2P networking module (py-libp2p-based).
Test Suite
tests/test_*.py (13 files)
Comprehensive tests for block hashing/merkle validation/coinbase, chain management/forks/reorg, PoW mining/difficulty/stop events, crypto key operations/signatures, genesis initialization, mempool deduplication/fees/eviction/nonce gaps, merkle trees, canonical serialization, state transitions/atomicity, transactions/signing, and module scaffolding imports.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Client
    participant ChainManager as ChainManager
    participant Block as Block
    participant State as State
    participant Mempool as Mempool

    Client->>ChainManager: add_block(block)
    ChainManager->>ChainManager: Check duplicate & known parent
    ChainManager->>Block: Validate merkle root & coinbase
    alt Block valid
        ChainManager->>State: Replay state along candidate path
        State-->>ChainManager: Updated state
        ChainManager->>ChainManager: Validate consensus (PoW, difficulty)
        ChainManager->>ChainManager: Decision: extend/reorg/fork
        ChainManager->>ChainManager: Update canonical chain & tip
        ChainManager->>Mempool: Remove confirmed transactions
        ChainManager-->>Client: Return tx_id
    else Block invalid
        ChainManager-->>Client: Raise ChainValidationError
    end
Loading

Estimated Code Review Effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly Related PRs

Suggested Labels

Python Lang, Make Lang, Documentation

Suggested Reviewers

  • Zahnentferner

Poem

🐰 Hops excitedly through merkle trees
A blockchain born from consensus dreams,
With blocks that hash and chains that link,
Transactions signed with crypto-ink,
The foundation laid, the network's test—
Chef's kiss — this MiniChain is blessed! 🌟

🚥 Pre-merge checks | ✅ 2
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat: chain manager with longest-chain fork resolution and state replay' accurately and specifically describes the main change in this PR, which implements a ChainManager that maintains canonical chain state, validates blocks, handles fork resolution, and performs state replay.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Tip

Issue Planner is now in beta. Read the docs and try it out! Share your feedback on Discord.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@arunabha003
Copy link
Author

Superseded by #34. Closing this PR to keep review history in one place.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant